//
// Description: 845. 八数码
// Created by Loading on 2022/6/26.
//

#include <bits/stdc++.h>

using namespace std;

int main() {
    // 初始状态
    string start;
    for (int i = 0; i < 9; ++i) {
        char c;
        cin >> c;
        start += c;
    }

    // 结束状态
    string res = "12345678x";
    auto bfs = [&]() {
        queue<string> q;
        // 每种状态下的最短距离
        unordered_map<string, int> d;

        q.emplace(start);
        d[start] = 0;

        int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};
        while (!q.empty()) {
            string s = q.front();
            q.pop();
            int dist = d[s];
            if (s == res) {
                return dist;
            }

            // 找到字符串存储中的二维坐标
            int index = s.find('x');
            int x = index / 3, y = index % 3;
            // 四个方向移动
            for (int i = 0; i < 4; ++i) {
                int a = x + dx[i], b = y + dy[i];
                if (a >= 0 && a < 3 && b >= 0 && b < 3) {
                    swap(s[index], s[a * 3 + b]);
                    if (d.find(s) == d.end()) {
                        // 更新距离
                        d[s] = dist + 1;
                        q.emplace(s);
                    }
                    swap(s[index], s[a * 3 + b]);
                }
            }
        }

        return -1;
    };

    cout << bfs() << endl;

    return 0;
}
